﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.IO;
using System.ComponentModel;

namespace sunsetmp.DialogWindow
{
    /// <summary>
    /// Interaction logic for DownloadWindow.xaml
    /// </summary>
    public partial class DownloadWindow : Window
    {
        Properties.Settings ps = Properties.Settings.Default;
        string track_name = null;
        WebClient webClient;

        public DownloadWindow(string url, string name)
        {
            InitializeComponent();
            WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal;
            this.Show();
            if (!File.Exists(ps.downDir + name))
            {
                DownloadTrack(url, name);
            }
            else
            {
                DialogWindow.DownloadQuestionWindow dw = new DialogWindow.DownloadQuestionWindow(this);
                dw.Request(url, name);
            }

        }

        public void DownloadTrack(string url, string name)
        {
            this.Title = "Загрузка " + name;
            this.Label.Content = name;
            name = RemoveConflictChars(name);
            track_name = name;
            webClient = new WebClient();
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
            if (ps.downDir == "")
            {
                ps.downDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads\\";
                ps.Save();
            }
            string downFile = ps.downDir;
            if (downFile[downFile.Length - 1] != '\\')
                downFile += "\\";
            downFile += name;
            webClient.DownloadFileAsync(new Uri(url), downFile);
        }

        private string RemoveConflictChars(string str)
        {
            string[] chars = {"\\", "|","/",":","*","\"","?","<",">"};
            foreach (string c in chars)
                str = str.Replace(c,"");
            return str;
        }


        private void CloseW_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void OfflineButton_Click(object sender, RoutedEventArgs e)
        {
            webClient.CancelAsync();
        }

        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            DownloadBar.Value = e.ProgressPercentage;
            TaskbarItemInfo.ProgressValue = (double)e.ProgressPercentage / 100;
        }

        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                if (File.Exists(ps.downDir + track_name))
                    File.Delete(@ps.downDir + track_name);
            }
            else
                if (e.Error != null)
                {
                    MessageBox.Show(e.Error.Message, "Ошибка при загрузке", MessageBoxButton.OK, MessageBoxImage.Error);
                    if (File.Exists(ps.downDir + track_name))
                        File.Delete(ps.downDir + track_name);
                }
            this.Close();
            return;
        }

        private void Border_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void Window_StateChanged_1(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Maximized)
                this.WindowState = System.Windows.WindowState.Normal;
        }
    }
}
